#include <iostream>
#include <unistd.h>
#include <vector>
#include "thread.hpp"
#include "LockGuard.hpp"

string GetThreadName()
{
    static int number = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", number++);
    return name;
}

int ticket = 10000;                                // 全局的共享资源
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 定义一个锁

void GetTicket(string name)
{
    while (true)
    {
        LockGuard lockguard(&mutex);
        { //代码块明确表明是临界区
            if (ticket > 0)
            {
                // 充当抢票花费的时间
                usleep(1000);
                printf("%s get a ticket : %d\n", name.c_str(), ticket);
                ticket--;
            }
            else
            {
                break;
            }
            // 实际情况, 还有后续的动作
        }
    }
}

int main()
{
    string name1 = GetThreadName();
    Thread<string> t1(name1, GetTicket, name1);

    string name2 = GetThreadName();
    Thread<string> t2(name2, GetTicket, name2);

    string name3 = GetThreadName();
    Thread<string> t3(name3, GetTicket, name3);

    string name4 = GetThreadName();
    Thread<string> t4(name4, GetTicket, name4);

    t1.start();
    t2.start();
    t3.start();
    t4.start();

    t1.join();
    t2.join();
    t3.join();
    t4.join();
    return 0;
}
